// packageA/pages/userAdd/userAdd.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';
import {
    relativeTimeThreshold
} from '../../../libs/moment.min.js';

Page({

    /**
     * 页面的初始数据
     */
    data: {


        //-------------------------------------------------------
        taskType: "1",
        // 从数据库获取的列表数据
        taskList: [],
        // 当前展开项的ID（初始不展开任何项）   
        activeName: null,
        //项目是否必填  
        isDepartRequired: true,
        //选择任务
        taskShow: false,
        //已选日常巡检数据
        listDayMap: {},
        //项目权限
        checkedProjectAll: false,
        //任务类型
        // taskType:null,
        //添加任务弹框
        addTaskShow: false,
        //任务对象
        initTaskObj: {},
        //审批流程
        taskApproval: new Map(),
        //页签
        cycle: 'day',
        //日常巡检数据
        dayData: {
            id: null,
            cycle: 'day',
            taskCheckedMap: new Map(),
        },
        //周常巡检数据
        weekData: {
            cycle: 'week',
            taskCheckedMap: new Map(),
        },
        //月常巡检数据
        monthData: {
            cycle: 'month',
            taskMonthMap: new Map(),
        },
        //当前选中页签的name
        tabsName: "day",
        //所有选中的任务
        taskAllMap: {},
        //
        // 动态频次列表：每个对象对应一个频次条目，周频次
        frequencyList: [],
        //动态频次列表，每个对象对应一个频次条目,月频次
        frequencyMonthList: [],
        weekDayArr: [{
                id: 1,
                name: "周一"
            },
            {
                id: 2,
                name: "周二"
            },
            {
                id: 3,
                name: "周三"
            },
            {
                id: 4,
                name: "周四"
            },
            {
                id: 5,
                name: "周五"
            },
            {
                id: 6,
                name: "周六"
            },
            {
                id: 7,
                name: "周日"
            },
        ],
        monthDayArr: [{
                id: 1,
                name: "1号"
            }, {
                id: 2,
                name: "2号"
            }, {
                id: 3,
                name: "3号"
            }, {
                id: 4,
                name: "4号"
            }, {
                id: 5,
                name: "5号"
            },
            {
                id: 6,
                name: "6号"
            }, {
                id: 7,
                name: "7号"
            }, {
                id: 8,
                name: "8号"
            }, {
                id: 9,
                name: "9号"
            }, {
                id: 10,
                name: "10号"
            },
            {
                id: 11,
                name: "11号"
            }, {
                id: 12,
                name: "12号"
            }, {
                id: 13,
                name: "13号"
            }, {
                id: 14,
                name: "14号"
            }, {
                id: 15,
                name: "15号"
            },
            {
                id: 16,
                name: "16号"
            }, {
                id: 17,
                name: "17号"
            }, {
                id: 18,
                name: "18号"
            }, {
                id: 19,
                name: "19号"
            }, {
                id: 20,
                name: "20号"
            },
            {
                id: 21,
                name: "21号"
            }, {
                id: 22,
                name: "22号"
            }, {
                id: 23,
                name: "23号"
            }, {
                id: 24,
                name: "24号"
            }, {
                id: 25,
                name: "25号"
            },
            {
                id: 26,
                name: "26号"
            }, {
                id: 27,
                name: "27号"
            }, {
                id: 28,
                name: "28号"
            }, {
                id: 29,
                name: "29号"
            }, {
                id: 30,
                name: "30号"
            },
            {
                id: 31,
                name: "31号"
            }
        ],
        currentIndx: 0,
        //周频次选中的值存到里面
        weekMap: {},
        //月频次选中的值存到里面
        monthMap: {},
        //月频次-显示选择几号
        weekMonthShow: false,
        //所有任务id
        taskAll: [],
        //id
        id: null,

        // 显示选择任务窗口
        showSelectedTask: false,
        taskList: [],
        checkedTaskItem: [],
        checkedAllTask: false,
        dailyTasks: [],
        showCheckedWeekWin: false,
        showCheckedMonthWin: false,
        weekDate: [],
        monthDate: [],
        deleteTask:{},
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        console.log(app.globalData.userInfo);
        let days = 'dayData.taskCheckedMap';
        let week = 'weekData.taskCheckedMap';
        let month = 'monthData.taskMonthMap';
        this.setData({
            [week]: new Map(),
            [days]: new Map(),
            [month]: new Map(),
            taskAllMap: new Map(),
            weekMap: new Map(),
            monthMap: new Map(),
        })
        console.log("0000000000000000");
        if (options.paramObj) {
            let paramObj = JSON.parse(options.paramObj);
            console.log('人员传参');
            console.log(paramObj);

            this.setData({
                paramObj: paramObj
            })

            if (paramObj.id) {
                let taskAllTaskMap = new Map();
                if (paramObj.dayData.dayTaskArr != null && paramObj.dayData.dayTaskArr.length > 0) {
                    let dayCheckMap = new Map();
                    paramObj.dayData.dayTaskArr.forEach(item => {
                        taskAllTaskMap.set(item.id, item)
                        dayCheckMap.set(item.id, item);
                    })
                    paramObj.dayData.taskCheckedMap = dayCheckMap
                }
                console.log(taskAllTaskMap);
                if (paramObj.frequencyList != null && paramObj.frequencyList.length > 0) {
                    paramObj.frequencyList.forEach(item => {
                        let weekDayMap = new Map();
                        item.weekArr.forEach(weekDayItem => {
                            weekDayMap.set(weekDayItem.id, weekDayItem);
                        })
                        item.weekDayMap = weekDayMap;
                        item.dayTaskArr.forEach(item1 => {
                            taskAllTaskMap.set(item1.id, item1)
                        })
                    })
                }
                if (paramObj.frequencyMonthList != null && paramObj.frequencyMonthList.length > 0) {
                    paramObj.frequencyMonthList.forEach(item2 => {
                        let monthDayMap = new Map();
                        item2.monthArr.forEach(monthDayItem => {
                            monthDayMap.set(monthDayItem.id, monthDayItem);
                        })
                        item2.monthDayMap = monthDayMap;
                        item2.dayTaskArr.forEach(item3 => {
                            taskAllTaskMap.set(item3.id, item3)
                        })
                    })
                }
                this.setData({
                    id: paramObj.id,
                    isEdit: true,
                    //编辑时显示头像
                    showUpload: false,
                    dayData: paramObj.dayData,
                    frequencyList: paramObj.frequencyList,
                    frequencyMonthList: paramObj.frequencyMonthList,
                    taskAllMap: taskAllTaskMap
                })
                //获取修改的数据
                this.getInfo();
            } else {
                //添加时显示上传头像组件
                this.setData({
                    showUpload: true
                })
            }
        }
        console.log(this.data);
      
        //查询审批流程
        this.findTaskApproval();

        // 删除
        let tArr = []
        for (let i = 1; i <= 30; i++) {
            tArr.push({
                id: i,
                name: "任务" + i,
                checked: false,
            });
        }
        this.setData({
            taskList: tArr
        });


        let wd = []
        let weekDays = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
        for (let i = 1; i <= weekDays.length; i++) {
            wd.push({
                id: i,
                name: weekDays[i - 1],
                checked: false,
            });
        }
        this.setData({
            weekDate: wd
        })

        let md = []
        for (let i = 1; i <= 31; i++) {
            md.push({
                id: i,
                name: i + "号",
                checked: false,
            });
        }
        this.setData({
            monthDate: md
        });
    },
    onTabChange(event) {
        let values = event.detail.name;
        this.setData({
            tabsName: values
        })
        // event.detail 的值为当前选中项的 name
        if (values == 'day') {
            let day = "dayData.cycle"
            this.setData({
                [day]: values,
            });
        }
      //   if (this.data.frequencyList.length==0){
      //       this.addFrequency();
      //   }
      //   if (this.data.frequencyMonthList.length==0){
      //     this.addFrequencyMonth();
      // }
    },
    //查询审批流程
    findTaskApproval() {
        console.log("查询审批流程");
        this.setData({
            taskList: []
        })

        let param = {
            isAuth: false,
            className: 'taskApprovalProcess',
            data: {
                sortFlag: 1,
                searchAll: true,
                selectFields: ['id', 'name', 'departMap', 'selectedDepartments', 'defaultApproval', 'member', 'sortFlag']
            }
        }
        CommonService.goFindList(param).then(res => {
            console.log(res);
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log("查询审批流程结果");
                console.log(result);
                console.log("result");
                this.setData({
                    taskApproval: result[0].departMap
                })
                console.log(this.data);
            }
        }).catch((error) => {})
    },
    // 折叠项切换事件
    onCollapseChange(event) {
        console.log(event);
        this.setData({
            activeName: event.detail
        });
    },

    // 主动控制展开指定项（例如点击按钮触发）
    expandItem(id) {
        this.setData({
            activeName: id
        });
    },
    //任务编辑按钮
    handleButtonClick(e) {
        console.log(e);
        // let taskEdit = e.currentTarget.dataset.taskObj
        const {
            taskList
        } = this.data;
        const taskEdit = taskList[e.currentTarget.dataset.index]
        this.setData({
            addTaskShow: true,
            initTaskObj: taskEdit
        })
    },

    //提交表单##
    confirmForm(e) {
        //避免表单重复提交-先禁用按钮
        this.setData({
            disabled: true
        })

        let obj = e.detail.value;
        let td = this.data;
        let editInfo = td.editInfo;
        console.log(obj);
        console.log(td);
        console.log(editInfo);
        let saveArr = [];
        let frequencyList = td.frequencyList;
        let frequencyMonthList = td.frequencyMonthList;
        let user = app.globalData.userInfo
        let dataAuthArr = [user.depart, user.departObj[0].companyId]
        let dataAuth = {
            depart: dataAuthArr
        }
        // 为每个数组的元素添加 type 字段，并合并到新数组
        saveArr = [
            ...frequencyList.map(item => ({
                ...item,
                dataAuthority: dataAuth
            })),
            ...frequencyMonthList.map(item => ({
                ...item,
                dataAuthority: dataAuth
            }))
        ];
        let dayData = td.dayData;
        dayData.dataAuthority = dataAuth
        saveArr.push(dayData);
        console.log(saveArr);
        const checkIds = saveArr.flatMap(item => item.dayTaskIdArr);
        console.log(checkIds);

        let param = {
            className: 'inspectionTaskPlan',
            data: {
                id: this.data.id,
                dayData: dayData,
                frequencyList: frequencyList,
                frequencyMonthList: frequencyMonthList,
                dataAuthority: dataAuth,
                taskArrId: checkIds,
            }
        }
        
        let union = [];
        let difference = [];
        if (checkIds.length>0 || this.data.taskAll.length>0){
          union = [...new Set([...checkIds, ...this.data.taskAll])];
          difference = this.data.taskAll.filter(
            item => !checkIds.includes(item)
          );
        }
        console.log(union);
        console.log(difference);
        console.log(saveArr);
        console.log(param);
        console.log("----------------------------------------");
        //避免表单重复提交
        Toast.loading({
            duration: 0,
            forbidClick: true,
            message: '数据提交中...'
        });
        console.log(param);
        CommonService.goSave(param).then(res => {
            console.log("res");
            console.log(res);
            this.setData({
                disabled: false
            })
            if (res.statusCode == 200 && res.data.success == true) {
                Toast.success('操作成功');
                //更新任务列表标记，已经选择的任务，下次不能再继续建
                if (union.length > 0) {
                    this.updateTaskRecordSgin(union, true)
                }
                if (difference.length > 0) {
                    this.updateTaskRecordSgin(difference, false)
                }
                setTimeout(() => {
                    //返回列表页并刷新数据
                    this.backAndRefresh();
                }, 1000);
            } else if (res.statusCode == 202) {
                Toast.fail('您操作太快了,请勿重复提交');
            } else {
                Toast.fail('操作失败');
            }
        }).catch((error) => {
            Toast.fail('操作失败');
        })
    },

    //更新任务列表，已经选择的任务打上标记，下次不能再选择
    updateTaskRecordSgin(union, checked) {
        let param = {
            className: 'taskReocrd',
            data: {
                filter: {
                    id: union
                },
                update: {
                    set: {
                        checked: checked
                    }
                }
            }
        }
        CommonService.goUpdate(param).then(res => {}).catch((error) => {})
    },


    //选择任务类型
    onchangetype(event) {
        console.log("event")
        console.log(event)
        this.setData({
            taskType: event.detail,
        });
        console.log(this.data.taskType);
    },

    //添加任务
    onAddTask() {
        console.log(this.data.taskList.length);
        const taskObj = {
            id: null,
            taskName: "",
            taskDescribe: "",
            taskRange: "",
            taskRequire: "",
            taskPrecautions: "",
            index: this.data.taskList.length
        }
        this.setData({
            addTaskShow: true,
            initTaskObj: taskObj
        })
    },

    //关闭任务弹出层
    onCloseTaskPopup() {
        this.setData({
            addTaskShow: false,
        })
    },

    //电子工牌数据同步es
    addElectronCard(id) {
        let param = {
            id: id
        }
        CommonService.electronCardSave(param).then(res => {
            if (res.statusCode == 200) {
                Toast.success('成功');
                setTimeout(() => {
                    //返回列表页并刷新数据
                    this.backAndRefresh();
                }, 1000);
            } else {
                Toast.fail('操作失败');
            }
        }).catch((error) => {
            Toast.fail('操作失败');
        })
    },

    //获取修改的数据
    getInfo() {
        let param = {
            id: this.data.id
        }

        CommonService.findPersonnel(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result) {
                let result = res.data.data.result;

                console.log('员工信息回显');
                console.log(result);

                //头像放数组中
                if (result.headImg) {
                    result.self_img = [result.headImg];
                }
                this.setData({
                    departInfo: {
                        id: result.depart,
                        name: result.departName
                    },
                    editInfo: result,
                    oldDepart: result.depart
                })
                console.log("result");
                console.log(result);
                let checkDetailArea = [];
                if (result.workAreaIdArrP) {
                    result.workAreaIdArrP.forEach(item => {
                        checkDetailArea.push(item + "")
                    })
                }

                this.setData({
                    checkDetailArea: checkDetailArea
                })

                //查询部门信息
                this.getDepartById(result.depart);
            }
        }).catch((error) => {})
    },

    //获取输入的数量
    onChangePartNum(event) {
        console.log("event");
        console.log(event);
        const {
            tabsName
        } = this.data
        console.log(this.data);
        if (tabsName == 'day') {
            let names = 'dayData.frequency'
            this.setData({
                [names]: 1
            })
        } else if (tabsName == 'week') {
            this.setData({
                [`frequencyList[${event.currentTarget.dataset.detail.index}].frequency`]: event.detail
            })
        } else if (tabsName == 'month') {
            this.setData({
                [`frequencyMonthList[${event.currentTarget.dataset.detail.index}].frequency`]: event.detail
            })
        }
        // let names = 'initTaskObj.imgCountRequire'
        // this.setData({
        //   [names]: event.detail
        // })
    },

    //非空验证（field要先去掉空格）
    formNotEmpty(field, messageField, messageCon) {
        if (!field) {
            let obj = {};
            obj[messageField] = messageCon;
            obj['disabled'] = true;
            this.setData(obj);
            return false;
        } else {
            return true;
        }
    },

    //验证imei是否重复
    isExistImei(imei) {
        let param = {
            imei: imei
        }

        return new Promise((resolve, reject) => {
            CommonService.findPersonnel(param).then(res => {
                if (res.data.data && res.data.data.result && res.data.data.result.imei) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            }).catch((error) => {
                resolve(false);
            })
        });
    },

    //添加任务弹框中确定事件
    onConfirmTask(e) {
        console.log(e);
        console.log(this.data);
        const {
            taskList,
            initTaskObj
        } = this.data
        taskList[initTaskObj.index] = initTaskObj
        this.setData({
            taskList: taskList
        })
        this.onCloseTaskPopup();
    },




    //选择完项目确定事件
    onConfirmUser() {
        let tabsName = this.data.tabsName;
        console.log(tabsName);
        let listMap = this.data.taskAllMap;
        //map转成数组
        let arr = [...listMap.values()];


        if (tabsName == 'day') {
            let dayMap = this.data.dayData
           // let dayarr = [...dayMap.taskCheckedMap.values()]
           console.log(dayMap);
            let dayarr = Object.values(dayMap.taskCheckedMap)
            console.log(dayarr);
            this.changeTask(dayarr, 'dayData');
        }
        if (tabsName == 'week') {
            let weekData = this.data.weekData
            // let dayarr = [...weekData.taskCheckedMap.values()]
            let obj = this.data.frequencyList[this.data.currentIndx]
            let dayarr = Object.values(obj.taskCheckedMap)
            this.changeTask(dayarr, 'weekData');
        }
        if (tabsName == 'month') {
            let obj = this.data.frequencyMonthList[this.data.currentIndx]
            let dayarr = Object.values(obj.taskCheckedMap)
            this.changeTask(dayarr, 'monthData');
        }
        this.onCloseDepart();
    },

    changeTask(taskArr, objectName) {
        let dayarr = taskArr
        let dayShowTaskName = []
        let dayTaskIdArr = []
        let dayTaskArr = []
        dayarr.forEach(item => {
            dayShowTaskName.push(item.name);
            dayTaskIdArr.push(item.id);
            dayTaskArr.push(item);
        });
        let dayShow = objectName + '.dayShowName';
        let dayTaskIdArrName = objectName + '.dayTaskIdArr';
        let dayTaskArrName = objectName + '.dayTaskArr';
        this.setData({
            [dayShow]: dayShowTaskName,
            [dayTaskIdArrName]: dayTaskIdArr,
            [dayTaskArrName]: dayTaskArr
        })
        if (objectName == 'weekData') {
            this.setData({
                [`frequencyList[${this.data.currentIndx}]`]: {
                    ...this.data.frequencyList[this.data.currentIndx],
                    dayShowTaskName: dayShowTaskName,
                    dayTaskIdArr: dayTaskIdArr,
                    dayTaskArr: dayTaskArr
                }
            })
        } else if (objectName == 'monthData') {
            this.setData({
                [`frequencyMonthList[${this.data.currentIndx}]`]: {
                    ...this.data.frequencyMonthList[this.data.currentIndx],
                    dayShowTaskName: dayShowTaskName,
                    dayTaskIdArr: dayTaskIdArr,
                    dayTaskArr: dayTaskArr
                }
            })
        }
    },
    //选择完周确定事件
    onConfirmWeek() {
        let listMap = this.data.weekMap;
        //map转成数组
        let arr = [...listMap.values()];
        console.log(arr);
        let dayValue = []
        let dayShowName = []
        let weekArr = []
        arr.forEach(item => {
            dayShowName.push(item.name);
            dayValue.push(item.id);
            weekArr.push(item);
        });
        let obj = this.data.frequencyList[this.data.currentIndx]
        obj.dayValue = dayValue
        obj.dayShowName = dayShowName
        obj.weekArr = weekArr
        obj.weekDayMap = listMap
        this.data.frequencyList[this.data.currentIndx] = obj
        this.setData({
            frequencyList: this.data.frequencyList
        })
        console.log(this.data);
        this.onCloseWeekDayShow();
    },

    //选择完月确定事件
    onConfirmMonth() {
        let listMap = this.data.monthMap;
        //map转成数组
        let arr = [...listMap.values()];
        console.log(arr);
        let dayValue = []
        let dayShowName = []
        let monthArr = []
        arr.forEach(item => {
            dayShowName.push(item.name);
            dayValue.push(item.id);
            monthArr.push(item);
        });
        let obj = this.data.frequencyMonthList[this.data.currentIndx]
        obj.dayValue = dayValue
        obj.dayShowName = dayShowName
        obj.monthArr = monthArr
        obj.monthDayMap = listMap
        console.log(obj);
        this.data.frequencyMonthList[this.data.currentIndx] = obj
        this.setData({
            frequencyMonthList: this.data.frequencyMonthList
        })
        console.log(this.data);
        this.onCloseMonthDayShow();
    },


    //选择周时间
    onWeekCheck({
        currentTarget
    }) {
        let detail = currentTarget.dataset.detail;
        let weekDayArr = this.data.weekDayArr;
        console.log(detail);
        console.log(weekDayArr);
        console.log(this.data.currentIndx);
        console.log(this.data.frequencyList[this.data.currentIndx]);
        let weekMap = this.data.weekMap
        weekDayArr.forEach(item => {
            if (item.id == detail.id) {
                item.checked = !item.checked;
                if (item.checked) {
                    weekMap.set(item.id, item);
                } else {
                    weekMap.delete(item.id);
                }
            }
        })
        //列表是否全被选中了
        let flag = weekDayArr.every(item => {
            return item.checked;
        });

        //是否选中全选
        if (flag) {
            this.setData({
                checkedAll: true
            })
        } else {
            this.setData({
                checkedAll: false
            })
        }
        console.log(weekMap);
        this.setData({
            weekDayArr: weekDayArr,
            weekMap: weekMap
        })
    },


    //选择周时间
    onMonthCheck({
        currentTarget
    }) {
        let detail = currentTarget.dataset.detail;
        let monthDayArr = this.data.monthDayArr;
        let monthMap = this.data.monthMap
        monthDayArr.forEach(item => {
            if (item.id == detail.id) {
                item.checked = !item.checked;
                if (item.checked) {
                    monthMap.set(item.id, item);
                } else {
                    monthMap.delete(item.id);
                }
            }
        })
        //列表是否全被选中了
        let flag = monthDayArr.every(item => {
            return item.checked;
        });

        //是否选中全选
        if (flag) {
            this.setData({
                checkedAll: true
            })
        } else {
            this.setData({
                checkedAll: false
            })
        }
        this.setData({
            monthDayArr: monthDayArr,
            monthMap: monthMap
        })
    },





    //选择项目事件
    onChangeProjectCheck({
        currentTarget
    }) {
        let detail = currentTarget.dataset.detail;
        let list = this.data.taskList;
        let taskAllMap = this.data.taskAllMap;
        let tabsName = this.data.tabsName

        let taskDayMap = this.data.dayData.taskCheckedMap;
        console.log(detail);
        console.log(taskDayMap);
        console.log(this.data);
        console.log(list);
   
        //let taskCheckedMap = this.data.weekData.taskCheckedMap
        let taskWeekMap = {}
        let taskMonthMap = {}
        if (this.data.tabsName == 'week') {
            let obj = this.data.frequencyList[this.data.currentIndx]
            taskWeekMap = obj.taskCheckedMap
        } else if (this.data.tabsName == 'month') {
            let obj = this.data.frequencyMonthList[this.data.currentIndx]
            taskMonthMap = obj.taskCheckedMap
        }
        list.forEach(item => {
            if (item.id == detail.id) {
                //点击复选框时切换选中
                item.checked = !item.checked;
                if (item.checked) {
                    //选中的放入已选列表，利用map避免重复
                    taskAllMap.set(item.id, item);
                    if (tabsName == 'day') {
                        item.cycle = "day"
                        taskDayMap[item.id] = item
                    } else if (tabsName == 'week') {
                        item.cycle = "week"
                        item.taskIndex = tabsName + this.data.currentIndx
                        //taskCheckedMap.set(item.id,item)
                        taskWeekMap[item.id] = item
                    } else {
                        item.cycle = "month"
                        item.taskIndex = tabsName + this.data.currentIndx
                        //taskCheckedMap.set(item.id,item)
                        taskMonthMap[item.id] = item
                    }
                } else {
                    //未选中的从map中删除
                    taskAllMap.delete(item.id);
                    if (tabsName == 'day') {
                        //taskDayMap.delete(item.id)
                        delete taskDayMap[item.id]
                    } else if (tabsName == 'week') {

                        delete taskWeekMap[item.id]
                    } else {
                        delete taskMonthMap[item.id]
                    }
                }
            }
        });

        //列表是否全被选中了
        let flag = list.every(item => {
            return item.checked;
        });

        //是否选中全选
        if (flag) {
            this.setData({
                checkedAll: true
            })
        } else {
            this.setData({
                checkedAll: false
            })
        }
        if (tabsName == 'day') {
            let taskDayMapName = "dayData.taskCheckedMap"
            this.setData({
                [taskDayMapName]: taskDayMap,
            })
        }
        if (tabsName == 'week') {
            this.setData({
                [`frequencyList[${this.data.currentIndx}].taskCheckedMap`]: taskWeekMap
            });
            // let taskCheckedMapName = "weekData.taskCheckedMap"
            // this.setData({
            //   [taskCheckedMapName]:taskCheckedMap,
            // })
        }
        if (tabsName == 'month') {
            this.setData({
                [`frequencyMonthList[${this.data.currentIndx}].taskCheckedMap`]: taskMonthMap
            });
        }
        this.setData({
            taskList: list,
            taskAllMap: taskAllMap,
        })

        console.log(this.data);

    },

    //验证手机号是否重复
    isExist(phone) {
        let param = {
            isAuth: false,
            className: 'user',
            data: {
                nbl: Base64.encode(util.timeFormatDay(new Date())),
                complex: [{
                    or: {
                        "userName": phone,
                        "personalPhone": phone
                    }
                }],
                selectFields: ["id"]
            }
        }

        return new Promise((resolve, reject) => {
            CommonService.goFindList(param).then(res => {
                if (res.data.data && res.data.data.result && res.data.data.result.length) {
                    resolve(true);
                } else {
                    resolve(false);
                }
            }).catch((error) => {
                resolve(false);
            })
        });
    },
    clearMessage111(e) {
        console.log("0900000000000009090");
        console.log(e);
    },
    //用户输入时清除错误提示
    clearMessage(e) {
        console.log("0000000000000099999999999999999999999999");
        console.log(e);
        let field = e.target.dataset.message;
        let obj = {};
        obj[field] = "";
        obj['disabled'] = false;
        this.setData(obj);
        const value = e.detail;
        let names = 'initTaskObj.' + field
        // 更新 initTaskObj.name
        this.setData({
            [names]: value
        });
    },

    //任务对象赋值
    setValue(e) {
        console.log(e);
        const fieldName = e.currentTarget.dataset.message;
        console.log(fieldName);

    },



    //扫码
    onScanCode(e) {
        var _this = this;
        wx.scanCode({
            success: (res) => {
                let imei = 'editInfo.imei';
                let results = res.result;

                //过滤掉'imei'
                if (results.indexOf('IMEI:') != -1) {
                    results = results.substring(5);
                }

                _this.setData({
                    [imei]: results
                })
            }
        })
    },

    //添加周频次
    addFrequency() {
      console.log("11");
       let frequencyWeekList= this.data.frequencyList;
        console.log(frequencyWeekList);
        const initTask = {
            id: null,
            index: frequencyWeekList.length,
            cycle: 'week',
            taskCheckedMap: {},
            imgCountRequire: 1, // 频次数量（默认1）
            dayShowName: [], // 周几显示文本（如"周一、周三"）
            dayValue: [], // 周几实际值（如[1,3]，用于提交）
            frequency: 1,
            weekDayMap: null
        }
        frequencyWeekList.push(initTask);
        this.setData({
            frequencyList: frequencyWeekList
        })
    },

    //添加月频次
    addFrequencyMonth() {
        const {
            frequencyMonthList
        } = this.data
        const initTask = {
            id: null,
            index: frequencyMonthList.length,
            cycle: 'month',
            taskCheckedMap: {},
            imgCountRequire: 1, // 频次数量（默认1）
            dayShowName: [], // 显示几号文本（如"周一、周三"）
            dayValue: [], // 几号实际值（如[1,3]，用于提交）
            frequency: 1,
            taskMonthMap: null
        }
        frequencyMonthList.push(initTask);
        this.setData({
            frequencyMonthList: frequencyMonthList
        })
    },

    //显示周几
    onWeekDay({
        currentTarget
    }) {
        console.log(currentTarget);
        if (currentTarget.dataset.detail.index != this.data.currentIndx) {
            this.setData({
                weekMap: new Map()
            })
        }
        this.setData({
            currentIndx: currentTarget.dataset.detail.index,
            weekDayShow: true
        })
        this.getWeekDay();
    },

    onMonthDay({
        currentTarget
    }) {
        console.log(currentTarget);
        if (currentTarget.dataset.detail.index != this.data.currentIndx) {
            this.setData({
                monthMap: new Map()
            })
        }
        this.setData({
            currentIndx: currentTarget.dataset.detail.index,
            monthDayShow: true
        })
        // this.getTasktList();
        this.getMonthDay();
    },

    getMonthDay() {
        let map = new Map();
        const {
            frequencyMonthList
        } = this.data
        let obj = frequencyMonthList[this.data.currentIndx]
        console.log("obj");
        console.log(obj);
        if (obj.monthDayMap != null) {
            let monthMapList = [...obj.monthDayMap.values()]
            monthMapList.forEach(item2 => {
                map.set(item2.id, item2);
            });
        }
        let projectList = this.data.monthDayArr;
        console.log("map");
        console.log(map);
        projectList.forEach(item => {
            if (map.get(item.id)) {
                console.log("map.get(item.id)");
                console.log(map.get(item.id));
                item.checked = true;
            } else {
                item.checked = false;
            }
        });
        console.log();
        this.setData({
            listDayMap: map,
            monthDayArr: projectList
        })
    },

    getWeekDay() {
        let map = new Map();
        const {
            frequencyList
        } = this.data
        let obj = frequencyList[this.data.currentIndx]
        console.log(obj);
        if (obj.weekDayMap != null) {
            let weekMapList = [...obj.weekDayMap.values()]
            weekMapList.forEach(item2 => {
                map.set(item2.id, item2);
            });
        }
        let projectList = this.data.weekDayArr;
        console.log("map");
        console.log(projectList);
        projectList.forEach(item => {
            if (map.get(item.id)) {
                console.log(item);
                item.checked = true;
            } else {
                item.checked = false;
            }
        });
        console.log();
        this.setData({
            listDayMap: map,
            weekDayArr: projectList
        })
    },


    //显示任务
    onShowDepart({
        currentTarget
    }) {
      console.log(currentTarget);
        console.log(this.data.tabsName);
        if (this.data.tabsName == 'week') {
            this.setData({
                currentIndx: currentTarget.dataset.detail.index,
                showSelectedTask: true
            })
        } else {
            this.setData({
              showSelectedTask: true
            })
        }
        console.log(this.data.deleteTask);
        this.getTasktList();
    },
    isSelectedByOtherCell(imei) {
        const {
            selectedPersonnel,
            currentCellId
        } = this.data;
        return selectedPersonnel[imei] && selectedPersonnel[imei] !== currentCellId;
    },
    //查询任务列表
    getTasktList() {
        let deleteTask = this.data.deleteTask;
        console.log("111111111111");
        console.log(this.data.tabsName);
        console.log(this.data);
        console.log(deleteTask);
        const {
            taskAllMap
        } = this.data
        this.setData({
            taskList: []
        })

        let param = {
            isAuth: false,
            className: 'taskReocrd',
            data: {
                searchAll: true,
                taskType: 2,
                selectFields: ['id', 'taskObj', 'projectArr', 'projectIds', 'taskType', 'createUser', 'createLevel', 'checked']
            }
        }
        CommonService.goFindList(param).then(res => {
            console.log(res);
            console.log("任务列表");
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                console.log("11111");
                let result = res.data.data.result;
                let arr = [];
                let taskAll = [];
                var checkedName = []
                result.forEach(item => {
                    let flg = item.checked
                    console.log(item.id in deleteTask);
                    if (item.id in deleteTask){
                      flg = false;
                    }
                    arr.push({
                        name: item.taskObj.taskName,
                        id: item.id,
                        obj: item,
                        disabled: flg,
                        checked: flg
                    });
                    taskAll.push(item.id);
                });
                console.log("result");
                console.log(arr);
                let map = new Map();
                console.log(taskAllMap);
              
                let taskAllList = [...taskAllMap.values()]
                taskAllList.forEach(item2 => {
                    map.set(item2.id, item2);
                });

                let projectList = arr;
                console.log("map");
                console.log(map);
                projectList.forEach(item => {
                    if (map.get(item.id)) {
                        console.log("map.get(item.id)");
                        console.log(map.get(item.id));
                        let mapVal = map.get(item.id);
                        console.log(this.data.tabsName);
                        console.log(mapVal.taskIndex);
                        if (mapVal.cycle != this.data.tabsName) {
                            item.disabled = true;
                        } else {
                            if (this.data.tabsName == 'week') {
                                if (this.data.tabsName + this.data.currentIndx == mapVal.taskIndex) {
                                    item.disabled = false;
                                } else {
                                    item.disabled = true;
                                }
                            } else if (this.data.tabsName == 'day') {
                                item.disabled = false;
                            }

                        }
                        console.log(item);
                        item.checked = true;
                    }
                });
                console.log(projectList);
                this.setData({
                    checkedTaskItem:checkedName,
                    listDayMap: map,
                    taskList: projectList,
                    taskAll: taskAll
                })
            }
            console.log("this.data");
            console.log(this.data);
        }).catch((error) => {})
    },

    //隐藏部门
    onCloseDepart() {
        this.setData({
          showSelectedTask: false,
        })
    },

    //隐藏周的选择
    onCloseWeekDayShow() {
        this.setData({
          showCheckedWeekWin: false,
        })
    },

    //隐藏月的选择
    onCloseMonthDayShow() {
        this.setData({
          showCheckedMonthWin: false,
        })
    },

    //确认部门
    onConfirmDepart(e) {
        let oldDepart = this.data.oldDepart;
        if (oldDepart && oldDepart != e.detail.value.id) {
            this.onCloseDepart();
            Dialog.confirm({
                title: '确定修改所属部门吗？',
                message: '修改后当前人员的排班将删除',
                confirmButtonText: '确定',
                cancelButtonText: '不改了'
            }).then(() => {
                this.departValue(e.detail.value);
                this.setData({
                    isEditDepart: true
                })
            }).catch(() => {
                this.setData({
                    isEditDepart: false
                })
            });
        } else {
            this.departValue(e.detail.value);
        }
    },

    //确认部门的值
    departValue(val) {
        let depart = 'editInfo.depart';
        let departName = 'editInfo.departName';
        let regionId = 'editInfo.regionId';
        let obj = val.obj;

        this.setData({
            [depart]: val.id,
            [departName]: val.text,
            //项目的大区(无大区取上级)存入工牌的数据权限
            [regionId]: obj.regionId ? obj.regionId : obj.fid,
            //选择的部门信息，用于匹配考勤规则和围栏
            departInfo: obj,
            disabled: false
        })

        this.onCloseDepart();
    },

    //搜索部门
    onChangeDepartVal(e) {
        this.setData({
            valueSearchDepart: e.detail
        })
        this.getDepartList();
    },

    //获取图片上传组件的传值
    getUploadUrl(data) {
        let imgUrls = data.detail;

        if (imgUrls.length) {
            this.setData({
                imgUrls: imgUrls
            })
        }
    },

    //返回列表页并刷新数据
    backAndRefresh() {
        let pages = getCurrentPages();
        let prevPage = pages[pages.length - 2];

        prevPage.refreshListAndPage();
        wx.navigateBack();
    },

    //显示考勤规则
    onShowRule() {
        if (this.data.editInfo.depart) {
            this.setData({
                showRule: true
            })
            this.getRuleList();
        } else {
            Toast.fail('请先选择部门');
        }
    },

    //查询考勤规则
    getRuleList() {
        let param = {
            isAuth: false,
            className: 'clockRule',
            data: {
                searchAll: true,
                selectFields: ['id', 'ruleName']
            }
        }

        //查询选择的部门、上级部门、大区、顶级部门的考勤规则
        try {
            let info = this.data.departInfo;
            let arr = [info.id];
            if (info.companyId) {
                arr.push(info.companyId);
            }
            if (info.fid) {
                arr.push(info.fid);
            }
            if (info.regionId) {
                arr.push(info.regionId);
            }
            param.data.departId = arr;
        } catch (e) {}

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                let arr = [];
                result.forEach(item => {
                    arr.push({
                        text: item.ruleName,
                        id: item.id
                    });
                });
                this.setData({
                    ruleList: arr
                })
            }
        }).catch((error) => {})
    },

    //隐藏考勤规则
    onCloseRule() {
        this.setData({
            showRule: false
        })
    },

    //确认考勤规则
    onConfirmRule(e) {
        let clockRuleId = 'editInfo.clockRuleId';
        let clockRuleName = 'editInfo.clockRuleName';
        this.setData({
            [clockRuleId]: e.detail.value.id,
            [clockRuleName]: e.detail.value.text,
            disabled: false
        })
        this.onCloseRule();
    },

    //显示围栏
    onShowFence() {
        if (this.data.editInfo.depart) {
            this.setData({
                showFence: true
            })
            this.getFenceList();
        } else {
            Toast.fail('请先选择部门');
        }
    },

    //查询围栏
    getFenceList() {
        let param = {
            isAuth: false,
            className: 'personnelFence',
            data: {
                searchAll: true,
                selectFields: ['id', 'name']
            }
        }

        //查询选择的部门、上级部门、大区、顶级部门的围栏
        try {
            let info = this.data.departInfo;
            let arr = [info.id];
            if (info.companyId) {
                arr.push(info.companyId);
            }
            if (info.fid) {
                arr.push(info.fid);
            }
            if (info.regionId) {
                arr.push(info.regionId);
            }
            param.data.departId = arr;
        } catch (e) {}

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                let arr = [];
                result.forEach(item => {
                    arr.push({
                        text: item.name,
                        id: item.id
                    });
                });
                this.setData({
                    fenceList: arr
                })
            }
        }).catch((error) => {})
    },

    //隐藏围栏
    onCloseFence() {
        this.setData({
            showFence: false
        })
    },

    //确认围栏
    onConfirmFence(e) {
        let fenceId = 'editInfo.fenceId';
        let fenceName = 'editInfo.fenceName';
        this.setData({
            [fenceId]: e.detail.value.id,
            [fenceName]: e.detail.value.text,
            disabled: false
        })
        this.onCloseFence();
    },

    //显示人员选择框
    onShowMessages() {
        this.setData({
            showMessages: true
        })
        //查询人员
        this.getUserList();
    },

    //查询人员
    getUserList() {
        let param = {
            depart: [this.data.editInfo.depart]
        }

        CommonService.findPersonnelAll(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                let arr = [];
                result.forEach(item => {
                    arr.push({
                        id: item.id,
                        name: item.nickName
                    });
                });

                this.setData({
                    userList: arr,
                    checkLen: arr.length
                })
            }
        }).catch((error) => {})
    },

    //隐藏项目选择框
    onCloseMessages() {
        this.setData({
            showMessages: false
        })
    },

    //勾选人员
    onChangeUser(event) {
        this.setData({
            messagesId: event.detail
        })

        if (event.detail.length == this.data.checkLen) {
            this.setData({
                checkedAll: true,
            })
        } else {
            this.setData({
                checkedAll: false,
            })
        }
    },

    //点击全选
    onChangeAll(event) {
        this.setData({
            checkedAll: event.detail,
        })

        if (event.detail) {
            let list = this.data.userList;
            let arr = [];
            list.forEach(item => {
                arr.push(item.id + "");
            })
            this.setData({
                messagesId: arr,
            })
        } else {
            this.setData({
                messagesId: [],
            })
        }
    },

    //确认人员
    onConfirmMessages() {
        let list = this.data.userList;
        let idArr = this.data.messagesId;

        let names = [];
        let arr = [];
        for (let i = 0; i < list.length; i++) {
            idArr.forEach(item => {
                if (item == list[i].id) {
                    names.push(list[i].name);
                    arr.push(list[i]);
                }
            });
        }

        let messagesName = 'editInfo.messagesName';
        let messagesReceivingUser = 'editInfo.messagesReceivingUser';
        this.setData({
            [messagesName]: names,
            [messagesReceivingUser]: arr
        })

        this.onCloseMessages();
    },

    //查询部门信息
    getDepartById(departId) {
        let param = {
            isAuth: false,
            className: 'depart',
            data: {
                id: departId,
                selectFields: ['id', 'name', 'regionId', 'region', 'fid', 'fDepart', 'companyId', 'company', 'area', 'type']
            }
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                this.setData({
                    departInfo: result[0]
                })
            }
        }).catch((error) => {})
    },

    //显示上传图片组件
    onShowUpload() {
        this.setData({
            showUpload: true
        })
    },

    //删除今天之后的排班
    deleteShift() {
        let param = {
            imei: this.data.editInfo.imei
        }
        CommonService.deleteShift(param).then(res => {}).catch((error) => {})
    },

    //显示选择框
    onShowSelect(e) {
        this.setData({
            selectList: []
        })

        let dataset = e.currentTarget.dataset;
        let field = dataset.field;

        //岗位
        if (field == 'jobPost') {
            //是否已选部门
            if (this.data.editInfo.departName) {
                this.setData({
                    showSelect: true,
                    selectField: field,
                    selectTitle: '岗位',
                    showSelectSearch: true
                })
                this.getStationStep();
            } else {
                Toast.fail('请选择部门');
                return;
            }

        } else {
            if (field == 'workArea') {
                this.setData({
                    selectTitle: '清洁区域',
                    showSelectSearch: true
                })
                this.getWorkAreaList();
            }

            if (field == 'jobDuty') {
                this.setData({
                    selectTitle: '岗位职责',
                    showSelectSearch: false,
                    selectList: this.data.jobDutyList
                })
            }

            this.setData({
                showSelect: true,
                selectField: field
            })
        }
    },

    //隐藏选择框
    onCloseSelect() {
        this.setData({
            showSelect: false,
            valueSearch: '',
            disabled: false
        })
    },

    //确认选项
    onConfirmSelect(e) {
        let selectField = this.data.selectField;
        let id = null,
            name = null,
            obj = null;

        //岗位
        if (selectField == 'jobPost') {
            console.log(e.detail.value.obj);

            //岗位id（表s_station_step中id）
            let stationStepId = 'editInfo.stationStepId';
            //岗位名称
            let jobPost = 'editInfo.jobPost';
            //岗位步数
            let fullStep = 'editInfo.fullStep';
            //工作时间
            let workTime = 'editInfo.workTime';

            let oo = e.detail.value.obj;

            //岗位职责选项
            let jobDutyList = [];
            if (oo.jobDuty && oo.jobDuty.length) {
                oo.jobDuty.forEach(item => {
                    jobDutyList.push({
                        id: item.id,
                        text: item.name
                    });
                });
            }

            this.setData({
                [stationStepId]: oo.stationStepId,
                [jobPost]: oo.jobPost,
                jobDutyList: jobDutyList,
                [fullStep]: oo.fullStep,
                [workTime]: oo.workTime,
            })
        }

        //清洁区域
        if (selectField == 'workArea') {
            id = 'editInfo.workAreaId';
            name = 'editInfo.workAreaName';
        }

        //岗位职责
        if (selectField == 'jobDuty') {
            id = 'editInfo.jobDutyId';
            name = 'editInfo.jobDutyName';
        }

        if (id && name) {
            this.setData({
                [id]: e.detail.value.id,
                [name]: e.detail.value.text
            })
        }

        if (obj) {
            this.setData({
                [obj]: e.detail.value.obj
            })
        }

        this.onCloseSelect();
    },

    //选择框搜索
    onChangeSelectVal(e) {
        let selectField = this.data.selectField;

        this.setData({
            valueSearch: e.detail
        })

        //岗位
        if (selectField == 'jobPost') {
            this.getStationStep();
        }
    },

    //改变选择框
    onChangeSelect() {
        let selectField = this.data.selectField;

        //改变岗位时清空职责
        if (selectField == 'jobPost') {
            console.log('11111111111');
            let jobDutyId = 'editInfo.jobDutyId';
            let jobDutyName = 'editInfo.jobDutyName';

            this.setData({
                [jobDutyId]: null,
                [jobDutyName]: null
            })
        }
    },

    //隐藏区域
    onCloseArea() {
        this.setData({
            showWorkAreaSelect: false
        })
    },

    //查询岗位
    getStationStep() {
        let departInfo = this.data.departInfo;

        let param = {
            isAuth: true,
            className: 'stationStep',
            data: {
                searchAll: true,
                //选择部门的顶级部门，这样任何用户登录都可以查到
                'member.id': departInfo.companyId,
                selectFields: ['id', 'name', 'step', 'jobDuty', 'workTime'],
                nbl: Base64.encode(util.timeFormatDay(new Date()))
            }
        }

        if (this.data.valueSearch) {
            param.data.name = '%' + this.data.valueSearch + '%';
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log('岗位');
                console.log(result);

                let arr = [];
                result.forEach(item => {
                    arr.push({
                        text: item.name,
                        id: item.id,
                        obj: {
                            stationStepId: item.id,
                            jobPost: item.name,
                            fullStep: item.step,
                            jobDuty: item.jobDuty,
                            workTime: item.workTime
                        }
                    });
                });

                this.setData({
                    selectList: arr
                })
            }
        }).catch((error) => {})
    },

    //改变部门
    onChangeDepart() {
        //清空岗位
        let stationStepId = 'editInfo.stationStepId';
        let jobPost = 'editInfo.jobPost';
        let fullStep = 'editInfo.fullStep';
        let jobDuty = 'editInfo.jobDuty';

        this.setData({
            [stationStepId]: null,
            [jobPost]: null,
            [fullStep]: null,
            [jobDuty]: null
        })
    },

    //查询清洁区域
    getWorkAreaList() {
        let param = {
            isAuth: true,
            className: 'workArea',
            data: {
                searchAll: true,
                selectFields: ['id', 'name', 'project']
            }
        }

        if (this.data.valueSearch) {
            param.data.name = '%' + this.data.valueSearch + '%';
        }

        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                let arr = [];
                result.forEach(item => {
                    arr.push({
                        text: item.name,
                        id: item.id,
                        obj: {
                            id: item.id,
                            name: item.name
                        }
                    });
                });

                this.setData({
                    selectList: arr
                })
            }
        }).catch((error) => {})
    },

    //-------------------------------------------工作区域---------------------------------------------------------------------------
    //显示工作区域选择框
    onShowWorkAreaPersonnel(e) {
        this.setData({
            selectWorkList: [],
        })
        if (this.data.editInfo.departName) {
            let dataset = e.currentTarget.dataset;
            let field = dataset.field;
            console.log(field);

            this.setData({
                selectTitle: "工作区域",
                showWorkAreaSelect: true,
                selectField: field
            })

            this.getWorkAreaPList();
        } else {
            Toast.fail('请选择项目');
            return;
        }
    },

    //查询工作区域
    getWorkAreaPList() {
        let departInfo = this.data.departInfo;
        console.log(this.data);
        let param = {
            isAuth: true,
            className: 'workAreaP',
            data: {
                searchAll: true,
                projectId: departInfo.id,
                selectFields: ['id', 'name', 'workAreaTypeName', 'attribute'],
                sort: {
                    workAreaTypeId: 1,
                    attribute: 1,
                    name: 1
                }
            }
        }

        if (this.data.valueSearch) {
            param.data.name = '%' + this.data.valueSearch + '%';
        }
        console.log(param);
        CommonService.goFindList(param).then(res => {
            if (res.data.data && res.data.data.result && res.data.data.result.length) {
                let result = res.data.data.result;
                console.log("result");
                console.log(result);
                let arr = [];
                result.forEach(item => {
                    arr.push({
                        id: item.id,
                        name: item.attribute + "-" + item.name,
                    });
                });

                this.setData({
                    selectWorkList: arr
                })
            }
        }).catch((error) => {})
    },


    //点击区域明细选项
    onChangeDetailArea(event) {
        console.log(event);
        this.setData({
            checkDetailArea: event.detail
        })

        if (event.detail.length == this.data.checkLenArea) {
            this.setData({
                checkedAllArea: true
            })
        } else {
            this.setData({
                checkedAllArea: false
            })
        }
    },


    //确定清洁区域按钮
    onConfirmArea() {
        console.log(this.data.checkDetailArea);
        let checkDetail = this.data.checkDetailArea;
        //所有工作区域
        if (checkDetail.length) {
            let list = this.data.selectWorkList;
            let arr = [];
            let names = [];
            let idarr = [];
            list.forEach(item => {
                for (let i = 0; i < checkDetail.length; i++) {
                    if (checkDetail[i] == item.id) {
                        console.log("相等");
                        arr.push(item);
                        names.push(item.name);
                        idarr.push(item.id);
                    }
                }
            });
            //显示名称
            let self_name = 'editInfo.workAreaNameP';
            //接口保存数据
            let items = 'editInfo.workAreaP';
            let self_ids = 'editInfo.workAreaIdArrP'
            this.setData({
                [self_name]: names,
                [items]: arr,
                [self_ids]: idarr,
                showWorkAreaSelect: false,
                disabled: false
            })
        } else {
            Toast.fail('请选择清洁区域');
        }
    },


    //-------------------------------------------工作区域---------------------------------------------------------------------------


    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    // -------------------------

    selectedTask() {
        console.log("selected task...");
        this.setData({
            showSelectedTask: true
        });
    },



    closeTaskWin() {
        this.setData({
            showSelectedTask: false
        });
    },

    removeTask(event) {
        const {tabsName} = this.data
        let taskObj = event.currentTarget.dataset.item;
        let taskArr = event.currentTarget.dataset.taskarr;
        let index = event.currentTarget.dataset.index;
        let deleteTask = this.data.deleteTask;
        deleteTask[taskObj.id] = taskObj;
        console.log("remove task...");
        console.log(tabsName);
        console.log(event);
        console.log(taskObj);
        console.log(taskArr);
        console.log("------------");
        let taskCheckedMapNew = {};
        let dayTaskArr = []
        let dayTaskIdArr = []
        let dayShowTaskName = []
        dayTaskArr = this.deleteObjectById(taskObj.id,taskArr)
        console.log(dayTaskArr)
        if (dayTaskArr.length!=0){
            dayTaskArr.forEach(item=>{
              taskCheckedMapNew[item.id] = item
              dayTaskIdArr.push(item.id);
              dayShowTaskName.push(item.name)
            })
        }
      
        if (tabsName == "day"){
          this.setData({
            [`dayData.taskCheckedMap`]: taskCheckedMapNew,
            [`dayData.dayTaskArr`]: dayTaskArr,
            [`dayData.dayTaskIdArr`]: dayTaskIdArr,
            [`dayData.dayShowTaskName`]: dayShowTaskName
          })
        }else if (tabsName == "week"){
          this.setData({
            [`frequencyList[${index[0]}].taskCheckedMap`]: taskCheckedMapNew,
            [`frequencyList[${index[0]}].dayTaskArr`]: dayTaskArr,
            [`frequencyList[${index[0]}].dayTaskIdArr`]: dayTaskIdArr,
            [`frequencyList[${index[0]}].dayShowTaskName`]: dayShowTaskName
          })
        }else if (tabsName == "month"){
          this.setData({
            [`frequencyMonthList[${index[0]}].taskCheckedMap`]: taskCheckedMapNew,
            [`frequencyMonthList[${index[0]}].dayTaskArr`]: dayTaskArr,
            [`frequencyMonthList[${index[0]}].dayTaskIdArr`]: dayTaskIdArr,
            [`frequencyMonthList[${index[0]}].dayShowTaskName`]: dayShowTaskName
          })
        }
        let taskAllMapNew = this.data.taskAllMap
        taskAllMapNew.delete(taskObj.id);
        this.setData({
          taskAllMap:taskAllMapNew,
          deleteTask:deleteTask
        })
        
        this.updateTaskRecordSgin([taskObj.id], false)
        console.log(this.data);
    },

    deleteObjectById(id,arr) {
        const index = arr.findIndex(item => item.id === id);
        if (index!== -1) {
          arr.splice(index, 1);
        }
        return arr;
    },
    searchTask() {
        console.log("search task...");
    },

    checkedTask(event) {
        console.log(event);
        console.log(event.detail);
        this.setData({
            checkedTaskItem: event.detail,
            checkedAllTask: this.data.checkedTaskItem.length === this.data.taskList.length
        });
    },

    checkedAllTask() {
        this.setData({
            checkedAllTask: !this.data.checkedAllTask
        });

        let names = []
        if (this.data.checkedAllTask) {
            for (let i = 0; i < this.data.taskList.length; i++) {
                this.data.taskList[i].checked = true;
                names.push(this.data.taskList[i].name);
            }
        }

        this.setData({
            checkedTaskItem: names
        });
    },

    confirm() {

        console.log("confirm...");
        console.log(this.data.active);
        console.log(this.data.checkedTaskItem);
        let selectTask = []
        if (!this.data.checkedAllTask) {
            for (let i = 0; i < this.data.taskList.length; i++) {
                let t = this.data.taskList[i]
                for (let j = 0; j < this.data.checkedTaskItem.length; j++) {
                    let name = this.data.checkedTaskItem[j]
                    if (name === t.name) {
                        selectTask.push(t)
                    }
                }
            }
        } else {
            selectTask = this.data.taskList;
        }
        console.log(selectTask);
        this.setData({
            dailyTasks: selectTask
        });
    },

    showCheckedFrequencyDateForWeek({currentTarget}) {
      console.log("currentTarget");
      console.log(currentTarget);
      if (currentTarget.dataset.detail.index != this.data.currentIndx){
        this.setData({
         weekMap:new Map()
        })
    }
    this.setData({
      currentIndx:currentTarget.dataset.detail.index,
			showCheckedWeekWin: true
    })
    this.getWeekDay()
    },

    closeCheckedFrequencyDateForWeek() {
        this.setData({
            showCheckedWeekWin: false
        });
    },

    selectWeekDay(event) {
        console.log(event);
        let item = event.target.dataset.item
        let index = event.target.dataset.index
        this.setData({
            [`weekDate[${index}].checked`]: !item.checked,
        });
    },

    confirmFreWeek() {
        console.log();
        let arr = []
        for (let i = 0; i < this.data.weekDate.length; i++) {
            let item = this.data.weekDate[i];
            if (item.checked) {
                arr.push(item);
            }
        }

        console.log(arr);
    },

    showCheckedFrequencyDateForMonth({currentTarget}) {
        console.log("currentTarget月");
        console.log(currentTarget);
        if (currentTarget.dataset.detail.index != this.data.currentIndx){
            this.setData({
             monthMap:new Map()
            })
        }
       this.setData({
         currentIndx:currentTarget.dataset.detail.index,
         showCheckedMonthWin: true
       })
      // this.getTasktList();
         this.getMonthDay();
    },
    closeCheckedFrequencyDateForMonth() {
        this.setData({
            showCheckedMonthWin: false
        });
    },

    selectMonthDay(event) {
        console.log(event);
        let item = event.target.dataset.item
        let index = event.target.dataset.index
        this.setData({
            [`monthDate[${index}].checked`]: !item.checked,
        });
    },

    confirmFreMonth() {
        console.log();
        let arr = []
        for (let i = 0; i < this.data.monthDate.length; i++) {
            let item = this.data.monthDate[i];
            if (item.checked) {
                arr.push(item);
            }
        }

        console.log(arr);
    },

    addWeekFre(){
        console.log("add week fre");
    },

    addMonthFre(){
        console.log("add month fre");
    },
})